package month5.Xmlproduct;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;

public class Xmlproducts {
    private final static String filePath = "E:\\Java8\\untitled\\java高级\\src\\month5\\Xmlproduct\\products.xml";
    public static Scanner in = new Scanner(System.in);

    public static void main(String[] args) {

        while (true) {
            System.out.println("1:读取商品信息,2:查找商品信息：根据输入的商品号,3:购买,4:增加新商品");

            int i = in.nextInt();
            if (i == 1) {
                readNode();
            } else if (i == 2) {
                System.out.println("输入商品编号");
                String str = in.next();
                readNode(str);
            } else if (i == 3) {
                System.out.println("输入商品号");
                String str = in.next();
                System.out.println("输入购买数量");
                int num = in.nextInt();
                double money = updateNode(str, num);
                if (money != 0)
                    System.out.println("应付款:" + money);

            } else if (i == 4) {
                System.out.println("输入是否折扣");
                String discount = in.next();
                System.out.println("输入工厂地址");
                String factoryaddr = in.next();
                System.out.println("输入商品编号");
                String itemno = in.next();
                System.out.println("输入商品名称");
                String name = in.next();
                System.out.println("输入商品单价");
                String price = in.next();
                System.out.println("输入计价单位");
                String stockcount = in.next();
                System.out.println("输入库存量");
                String unit = in.next();
                addNode(discount, factoryaddr, itemno, name, price, stockcount, unit);
            } else {

            }
        }
    }

    /**
     * 读取XML文件，获得document对象
     *
     * @return
     */
    private static Document getDoc() {
        SAXReader s = new SAXReader();
        Document doc = null;
        try {
            doc = s.read(new File(filePath));
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
        return doc;
    }

    /**
     * 读取products.xml中的商品信息，输出。
     */
    private static void readNode() {
        Document doc = getDoc();
        List<Node> nodeList = doc.selectNodes("//product");
        nodeList.forEach(node -> {
            if (node instanceof Element) {
                Element e = (Element) node;
                export(e);
                System.out.println("-------------------------------------------------------------------------");
            }
        });
    }

    /**
     * 查找商品信息：根据输入的商品号，输出对应的商品信息。
     *
     * @param ite 输入的商品号
     */
    private static void readNode(String ite) {
        Document doc = getDoc();
        Element root = doc.getRootElement();
        List<Element> list = root.elements("product");
        Element ele = list.stream().filter(element -> element.element("itemno").getText().equals(ite)).findFirst().orElse(null);
        if (ele != null) {
            export(ele);
        }{
            System.out.println("商品不存在");
        }

    }

    /**
     * 修改products.xml，输入商品编号（itemno）和数量，修改对应商品的数量（stockcount）；输出应付款的金额。
     *
     * @param ite 商品编号
     * @param num 购买商品数量
     */
    private static double updateNode(String ite, int num) {
        Document doc = getDoc();
        Element root = doc.getRootElement();
        List<Element> list = root.elements("product");
        Element ele = list.stream().filter(element -> element.element("itemno").getText().equals(ite)).findFirst().orElse(null);
        if (ele != null) {
            int number = Integer.parseInt(ele.element("stockcount").getText());
            if (number >= num) {
                String str = String.valueOf(number - num);
                ele.element("stockcount").setText(str);
                System.out.println("购买成功");
                saveToXml(doc);
                double pri = 0;
                double d = 0;
                if (ele.attributeValue("discount").equals("true")) {
                    d = Double.parseDouble(ele.element("price").getText());
                    pri = d * num * 0.7;
                } else
                    pri = d * num;
                return pri;
            } else {
                System.out.println("购买数量超过库存量");
            }
        } else {
            System.out.println("商品不存在");
        }
        return 0;
    }

    /**
     * 增加新商品的功能，要求商品号和商品名称都不能重复
     *
     * @param discount
     * @param factoryaddr
     * @param itemno
     * @param name
     * @param price
     * @param stockcount
     * @param unit
     * @return
     */
    private static boolean addNode(String discount, String factoryaddr, String itemno, String name, String price, String stockcount, String unit) {
        Document doc = getDoc();
        Element ele = doc.getRootElement();
        List<Node> nodeList = doc.selectNodes("//product");
        for (Node node : nodeList) {
            if (node instanceof Element) {
                Element e = (Element) node;
                String ite = e.elementTextTrim("itemno");
                String n = e.elementTextTrim("name");
                if (ite.equals(itemno) || n.equals(name)) {
                    System.out.println("商品号或商品名称重复");
                    return false;
                }
            }
        }
        ele.addElement("product")
                .addAttribute("discount", discount)
                .addAttribute("factoryaddr", factoryaddr)
                .addElement("itemno").addText(itemno)
                .getParent().addElement("name").addText(name)
                .getParent().addElement("price").addText(price)
                .getParent().addElement("stockcount").addText(stockcount)
                .getParent().addElement("unit").addText(unit);
        saveToXml(doc);
        System.out.println("增加成功");
        return true;
    }

    /**
     * 将文档写入XML文件
     *
     * @param doc
     */
    private static void saveToXml(Document doc) {
        XMLWriter out = null;
        try {
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("UTF-8");
            out = new XMLWriter(new FileWriter(new File(filePath)), format);

            out.write(doc);
            out.flush();
            System.out.println("success!!");
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 输出节点的商品信息
     *
     * @param e product节点
     */
    private static void export(Element e) {
        String discount = e.attributeValue("discount");
        String factoryaddr = e.attributeValue("factoryaddr");
        String itemno = e.elementTextTrim("itemno");
        String name = e.elementTextTrim("name");
        String price = e.elementTextTrim("price");
        String stockcount = e.elementTextTrim("stockcount");
        String unit = e.elementTextTrim("unit");
        System.out.println("是否折扣：" + discount + "\t工厂地址" + factoryaddr + "\t商品编号" + itemno + "\t商品名称" + name + "\t商品单价" + price + "\t计价单位" + unit + "\t库存量" + stockcount);
    }
}